import sensor
import time
from serial import Serial
import pyb
 
time.sleep(38)

thresholds = [
    (11, 46, 20, 65, 3, 63),  # red_thresholds
    (0, 100, -50, -12, -27, 24),  # green_thresholds
    (5, 19, -10, 13, -36, -7),  # blue_thresholds
]

ld1 = pyb.LED(1)
ld2 = pyb.LED(2)
ld3 = pyb.LED(3)

# 指示灯字典
d = {
    0: ld1,
    1: ld2,
    2: ld3
}

sensor.reset()
sensor.set_pixformat(sensor.RGB565)  # 设置图像格式为RGB565
sensor.set_framesize(sensor.QVGA)  # 设置图像大小为QVGA，
sensor.skip_frames(time=20)  # 使新设置生效，跳过20帧
sensor.set_auto_gain(False)  # 关闭自动增益
sensor.set_auto_whitebal(False)  # 关闭自动白平衡

serial = Serial()  # 创建串口对象

def detect_color(threshold:tuple):
    """识别颜色
    ----
    识别到对应的颜色后会给串口发送信号
    * threshold: 传入的阈值
    """
    sensor.set_pixformat(sensor.RGB565)  # 设置图像格式为RGB565
    while True:
        img = sensor.snapshot()
        img.lens_corr(1.8)
        for blob in img.find_blobs(
                [threshold],  # 选择颜色,0为红色,1为绿色,2为蓝色
                pixels_threshold=20000,  # 识别到的颜色块像素阈值
                area_threshold=20000,   # 识别到的颜色块面积阈值
                merge=True  # 合并颜色块
        ):
            if blob.rect() is not None: # 如果识别到颜色块
                return send()  # 发送信号给单片机,开始执行任务

def send():
    while 1:
        serial.write(b'1')  # 发送信号给单片机,开始执行任务

        
def detect_card() -> int:
    """识别色卡的颜色
    ----
    返回阈值表中的索引"""
    sensor.set_pixformat(sensor.RGB565)  # 设置图像格式为RGB565
    while True:
        img = sensor.snapshot()
        img.lens_corr(1.8)
        for i in range(3):
            for blob in img.find_blobs(
                    [thresholds[i]],            # 选择颜色,0为红色,1为绿色,2为蓝色
                    pixels_threshold=20000,     # 识别到的颜色块像素阈值
                    area_threshold=20000,       # 识别到的颜色块面积阈值
                    merge=True                  # 合并颜色块
            ):
                if blob.rect() is not None:
                    return i

if __name__ == '__main__':
    index = detect_card()
    d[index].on()                       # 亮起对应的灯
    time.sleep(2)                       # 防止误识别第一张色卡，这个数值要看情况调整
    detect_color(thresholds[index])
    pass
